package nl.cmkprojects.sage.slimplayer;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ArtistNameResolver
{
  private static final Pattern NowPlayingPatternByFrom = Pattern
      .compile("(.*) by (.*) from (.*)");

  private static final Pattern NowPlayingPatternFromBy = Pattern
      .compile("(.*) from (.*) by (.*)");

  private static final Pattern NowPlayingPatternBy = Pattern
      .compile("(.*) by (.*)");

  public static String resolveArtistName(String title)
  {
    String artist = null;
    if (title != null)
    {
      String[] parts = title.split(" - ");
      if (parts != null)
      {
        if (parts.length == 1)
        {
          // assume lastfm title with format:
          // <song-title> by <artist> from album>
          Matcher matcher = NowPlayingPatternByFrom.matcher(parts[0]);
          if (matcher.find() && matcher.groupCount() == 3)
          {
            artist = parts[0].substring(matcher.start(2), matcher.end(2))
                .trim();
          }
          // <song-title> from album by <artist>
          if (artist == null)
          {
            matcher = NowPlayingPatternFromBy.matcher(parts[0]);
            if (matcher.find() && matcher.groupCount() == 3)
            {
              artist = parts[0].substring(matcher.start(3), matcher.end(3))
                  .trim();
            }
          }
          // <song-title> by <artist>
          if (artist == null)
          {
            matcher = NowPlayingPatternBy.matcher(parts[0]);
            if (matcher.find() && matcher.groupCount() == 2)
            {
              artist = parts[0].substring(matcher.start(2), matcher.end(2))
                  .trim();
            }
          }

        } else
        {
          // assume shoutcast format: <artist> - < title>
          artist = parts[0];
        }
      }
    }
    return artist;
  }

  public static void main(String[] args)
  {
    System.out.println(ArtistNameResolver
        .resolveArtistName("walkon by Cool and by the Gang"));
    System.out.println(ArtistNameResolver
        .resolveArtistName("shjsh by Cool and the Gang"));
    System.out.println(ArtistNameResolver
        .resolveArtistName("shjsh from eternity by Cool and the Gang"));
    System.out.println(ArtistNameResolver
        .resolveArtistName("shjsh by Cool and the Gang from eternity"));
    System.out.println(ArtistNameResolver
        .resolveArtistName("Cool and the Gang - eternity"));
    System.out.println(ArtistNameResolver
        .resolveArtistName("Cool by the Gang - eternity"));
  }
}
